package com.xhsj.user.pms.oareply.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhsj.user.generalprocess.mapper.TbPamGeneralNodeMapper;
import com.xhsj.user.generalprocess.mapper.TbPamGeneralProcessHiTaskMapper;
import com.xhsj.user.generalprocess.vo.GeneralAuditHistoryVo;
import com.xhsj.user.hr.system.entity.TbGlobalUser;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.hr.system.query.UserNameInfo;
import com.xhsj.user.pms.common.constant.IdentifyConstant;
import com.xhsj.user.pms.oareply.dto.*;
import com.xhsj.user.pms.oareply.entity.TbPamPatentOaCorrection;
import com.xhsj.user.pms.oareply.service.TbPamPatentOaCorrectionService;
import com.xhsj.user.pms.oareply.vo.CorrectionFileListVo;
import com.xhsj.user.pms.oareply.vo.FindToAuditVo;
import com.xhsj.user.pms.patent.domain.TbPamOverseasApply;
import com.xhsj.user.pms.patent.vo.ProcessNodeVo;
import com.xhsj.user.pms.workflow.model.WorkFlowScheduleModel;
import com.xhsj.user.utils.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiOperation;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.*;
import java.util.stream.Collectors;

import com.xhsj.user.utils.Message;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;

import org.springframework.web.bind.annotation.RestController;


import com.xhsj.user.pms.oareply.service.TbPamPatentOaRecheckService;
import com.xhsj.user.pms.oareply.entity.TbPamPatentOaRecheck;

import javax.validation.Valid;


/**
 * <p>
 * 专利OA复审 前端控制器
 * </p>
 *
 * @author liuqinghua
 * @since Jul 28, 2021 8:20:11 AM
 */
@Slf4j
@Api(tags = "专利OA复审")
@RestController
@RequestMapping("/oareply/tbPamPatentOaRecheck")
public class TbPamPatentOaRecheckController {

    @Autowired
    public TbPamPatentOaRecheckService service;

    @Autowired
    public TbPamGeneralNodeMapper tbPamGeneralNodeMapper;

    @Autowired
    public TbPamGeneralProcessHiTaskMapper tbPamGeneralProcessHiTaskMapper;

    @Autowired
    public TbPamPatentOaCorrectionService tbPamPatentOaCorrectionService;

    @Autowired
    private TbGlobalUserMapper userMapper;

    /**
     * 保存/修改
     *
     * @author liuqinghua
     * @date Jul 28, 2021 8:20:11 AM
     */
    @ApiOperation(value = "专利OA复审,保存/修改", notes = "专利OA复审,保存和修改方法")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    // @PreAuthorize("hasAuthority('tb:pam:patent:oa:recheck:edit')")
    public Message save(@RequestBody TbPamPatentOaRecheck data) {
        try {
            service.save(data);
            return Message.success("成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1, "失败");
        }
    }

    /**
     * 通过id删除数据
     *
     * @author liuqinghua
     * @date Jul 28, 2021 8:20:11 AM
     */
    @ApiOperation(value = "专利OA复审删除", notes = "通过id删除专利OA复审信息。")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    // @PreAuthorize("hasAuthority('tb:pam:patent:oa:recheck:delete')")
    public Message delete(@RequestParam(value = "id") Long id) {
        try {
            service.removeById(id);
            return Message.success("成功");
        } catch (Exception e) {
            log.error("删除失败:{}", e);
            return Message.error(1, "失败");
        }
    }


    /**
     * 分页查询数据
     *
     * @author liuqinghua
     * @date Jul 28, 2021 8:20:11 AM
     */
    @ApiOperation(value = "分页查询专利OA复审list", notes = "带参数查询,{\"page\": 1,\"size\": 5,......}。支持模糊查询")
    @RequestMapping(value = "/findList", method = RequestMethod.POST)
    // @PreAuthorize("hasAuthority('tb:pam:patent:oa:recheck:view')")
    public Message findList(@RequestBody Map<String, Object> data) {
        try {
            IPage<TbPamPatentOaRecheck> selectPage = service.selectPage(data);
            return Message.success("成功", selectPage.getRecords(), selectPage.getTotal(), selectPage.getPages());
        } catch (Exception e) {
            log.error("查询异常:{}", e);
            return Message.error(1, "失败");
        }
    }

    /**
     * 查询所有数据
     *
     * @author liuqinghua
     * @date Jul 28, 2021 8:20:11 AM
     */
    @ApiOperation(value = "查询专利OA复审所有数据list", notes = "查询专利OA复审所有数据list。")
    @RequestMapping(value = "/findAll", method = RequestMethod.POST)
    // @PreAuthorize("hasAuthority('tb:pam:patent:oa:recheck:view')")
    public Message findAll() {
        return Message.success("成功", service.selectAll());
    }

    /**
     * 通过id获取实体类
     *
     * @author liuqinghua
     * @date Jul 28, 2021 8:20:11 AM
     */
    @ApiOperation(value = "通过id获取专利OA复审实体类", notes = "通过id获取专利OA复审实体类。")
    @RequestMapping(value = "/getById", method = RequestMethod.GET)
    public Message getById(@RequestParam(value = "id") Long id) {
        return Message.success("成功", service.getById(id));
    }

    /**
     * @Description: 专利OA驳回流程启动
     * @Author: liuqinghua
     * @Date: 2021/8/03
     */
    @ApiOperation(value = "专利OA驳回流程启动 ", notes = "专利OA驳回流程启动")
    @RequestMapping(value = "/startOARecheckProcess", method = RequestMethod.POST)
    public Message startOARecheckProcess(@RequestBody @Valid StartOARecheckProcessDto param, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return Message.error(1, bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            service.startOARecheckProcess(param);
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, e.getMessage());
        }
        return Message.success("成功");
    }

    /**
     * @Description:专利OA驳回-ipr/操作人审核/知识产权部\LED高级工艺工程师\总经理角色审核
     * @Author: liuqinghua
     * @Date: 2021/8/4
     */
    @ApiOperation(value = "ipr/操作人审核/专利OA驳回-知识产权部|LED高级工艺工程师|总经理角色审核", notes = "专专利OA驳回-知识产权部|" +
            "LED高级工艺工程师|总经理角色审核")
    @RequestMapping(value = "/iprZszl1LedGmProcess", method = RequestMethod.POST)
    public Message iprZszl1LedGmProcess(@RequestBody @Valid Zszl1LedGmProcessDto param, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return Message.error(1, bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            service.iprZszl1LedGmProcess(param);
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, e.getMessage());
        }
        return Message.success("成功");
    }

    /**
     * @Description: 专利OA驳回-国知局审查
     * @Author: liuqinghua
     * @Date: 2021/8/4
     */
    @ApiOperation(value = "专利OA驳回-国知局审查", notes = "专利OA驳回-国知局审查")
    @RequestMapping(value = "/examinationProcess", method = RequestMethod.POST)
    public Message examinationProcess(@RequestBody @Valid ExaminationProcessDto param, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return Message.error(1, bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            service.examinationProcess(param);
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, e.getMessage());
        }
        return Message.success("成功");
    }

    /**
     * @Description: 专利OA驳回-待审核
     * @Author: liuqinghua
     * @Date: 2021/8/3
     */
    @ApiOperation(value = "专利OA驳回-待审核", notes = "专利OA驳回-待审核")
    @RequestMapping(value = "/findToAudit", method = RequestMethod.POST)
    public Message findToAudit(@RequestBody @Valid FindToAuditDto param,BindingResult bindingResult) {
        try {
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1, bindingResult.getFieldError().getDefaultMessage());
            }
            IPage<FindToAuditVo> toAudit = service.findToAudit(param);
            return Message.success("成功", toAudit.getRecords(), toAudit.getTotal(), toAudit.getPages());
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "失败");
        }

    }

    /**
     * @Description: 专利OA驳回-审核通过
     * @Author: liuqinghua
     * @Date: 2021/8/3
     */
    @ApiOperation(value = "专利OA驳回-审核通过", notes = "专利OA驳回-审核通过")
    @RequestMapping(value = "/findApproved", method = RequestMethod.POST)
    public Message findApproved(@RequestBody @Valid FindToAuditDto param,BindingResult bindingResult) {
        try {
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1, bindingResult.getFieldError().getDefaultMessage());
            }
            IPage<FindToAuditVo> toAudit = service.findApproved(param);
            return Message.success("成功", toAudit.getRecords(), toAudit.getTotal(), toAudit.getPages());
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "失败");
        }

    }

    /**
     * @Description:专利OA驳回-获取驳回文件
     * @Author: liuqinghua
     * @Date: 2021/8/4
     */
    @ApiOperation(value = "专利OA驳回-获取驳回文件", notes = "专利OA补正-获取补正文件")
    @RequestMapping(value = "/findReCheckFileList", method = RequestMethod.GET)
    public Message findReCheckFileList(@RequestParam Long dataId,
                                        @RequestParam(value = "page", required = false) Long page,
                                        @RequestParam(value = "pageSize", required = false) Long pageSize) {
        try {
            IPage<CorrectionFileListVo> findCorrectionFileList = service.findReCheckFileList(dataId,page,pageSize);
            return Message.success("成功", findCorrectionFileList.getRecords(),findCorrectionFileList.getTotal(),findCorrectionFileList.getPages());
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "失败");
        }

    }

    /**
     * @Description:专利OA驳回-获取驳回文件不分页
     * @Author: liuqinghua
     * @Date: 2021/8/4
     */
    @ApiOperation(value = "专利OA驳回-获取驳回文件不分页", notes = "专利OA补正-获取驳回文件不分页")
    @RequestMapping(value = "/findReCheckFileListNotPage", method = RequestMethod.GET)
    public Message findReCheckFileListNotPage(@RequestParam Long dataId) {
        try {
            List<CorrectionFileListVo> findCorrectionFileList = service.findReCheckFileListNotPage(dataId);
            return Message.success("成功", findCorrectionFileList);
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "失败");
        }

    }

    /**
     * @Description: 流程进度
     * @Author: liuqinghua
     * @Date: 2021/8/5
     */
    @RequestMapping(value = "/getProgress", method = RequestMethod.GET)
    public Message getProgress(@RequestParam("dataId") Long dataId, @RequestParam("processType") String processType) {
        try {
            String nodeName = "";
            Long nodeId = null;
            switch (processType) {
                case "patent_bz":
                    TbPamPatentOaCorrection byIdc = tbPamPatentOaCorrectionService.getById(dataId);
                    nodeName = byIdc.getNodeName();
                    nodeId = byIdc.getNodeId();
                    break;
//                case "patent_oa":
//                    TbPamPatentOaRecheck byId = service.getById(dataId);
//                    processType = "patent_oa";
//                    break;
                case "patent_fs":
                    TbPamPatentOaRecheck byIdr = service.getById(dataId);
                    nodeName = byIdr.getNodeName();
                    nodeId = byIdr.getNodeId();
                    break;
            }
            JSONObject jsonObject = new JSONObject();
            int execOrder = 10;
            if ("闭案".equals(nodeName)) {
//                List<Map<String, Object>> opinionText = tbPamGeneralProcessHiTaskMapper.getNewNodeIdByDataId(dataId, processType);
                List<Map<String, Object>> opinionText = tbPamGeneralProcessHiTaskMapper.getNewNodeIdByDataId(dataId, processType);
                List<Map<String, Object>> collect = opinionText.stream()
                        .sorted(Comparator.comparing(e -> String.valueOf(e.get("updateDate"))))
                        .collect(Collectors.toList());
                execOrder = 9;
                jsonObject.put("nodeList", collect);
            } else {
//                List<ProcessNodeVo> list = tbPamGeneralNodeMapper.getNodeListByProcessType(processType);
                List<ProcessNodeVo> list = tbPamGeneralNodeMapper.getNodeListContainEndByProcessType(processType);
                String filterNodeName = null;
                if (!"诉讼".equals(nodeName)) {
                    filterNodeName = "诉讼";
                }else  if("诉讼".equals(nodeName)){
                    filterNodeName = "完结";
                }
                int finalNodeId = Integer.valueOf(Math.toIntExact(nodeId)).intValue();
                String finalFilterNodeName = filterNodeName;
                List<ProcessNodeVo> collect = list.stream().filter(processNodeVo ->
                        Objects.equals(processNodeVo.getNodeId(), finalNodeId) ||
                                !Objects.equals(processNodeVo.getNodeName(), finalFilterNodeName)).collect(Collectors.toList());

                jsonObject.put("nodeList", collect);
            }


            jsonObject.put("cutNodeId", nodeId);

            return Message.success("成功", jsonObject);
        } catch (Exception e) {
            log.error("失败:{}", e);
            return Message.error(1, e.getMessage());
        }
    }

    /**
     * @Description: 流程历史记录
     * @Author: liuqinghua
     * @Date: 2021/8/5
     */
    @ApiOperation(value = "流程历史记录", notes = "流程历史记录")
    @RequestMapping(value = "/getWorkFlowSchedule", method = RequestMethod.POST)
    public Message getWorkFlowSchedule(@RequestBody @Valid WorkFlowScheduleDto param,BindingResult bindingResult) {
        try {
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1, bindingResult.getFieldError().getDefaultMessage());
            }
            Page<GeneralAuditHistoryVo> page = new Page<>(param.getPage(), param.getPageSize());
            IPage<GeneralAuditHistoryVo> workFlowSchedule1 = tbPamGeneralProcessHiTaskMapper.getWorkFlowSchedule(page, param);
            List<GeneralAuditHistoryVo> records = workFlowSchedule1.getRecords();
            for (GeneralAuditHistoryVo workFlowSchedule : records) {
                StringBuilder sb = new StringBuilder();
                if (StringUtils.isNotBlank(workFlowSchedule.getUserId())) {
                    // 得到处理人
                    UserNameInfo userNameInfo = userMapper.getUserNameInfoByUserId(Long.valueOf(workFlowSchedule.getUserId()));
                    String status = "";
                    if (userNameInfo.getStatus() == 1)
                        status = "(已离职)";
                    workFlowSchedule.setUpdateName(userNameInfo.getFullName() + status);
                }
                if (StringUtils.isNotBlank(workFlowSchedule.getRoleId())) {
                    // 得到处理人
                    List<TbGlobalUser> userListByRoleId = userMapper.getUserListByRoleId(String.valueOf(workFlowSchedule.getRoleId()));
                    if (userListByRoleId != null) {
                        for (TbGlobalUser user : userListByRoleId) {
                            if (user.getStatus() == 0) {
                                sb.append(String.valueOf(user.getFullName() + " "));
                            }
                        }
                    }
                    workFlowSchedule.setUpdateName(sb.toString());
                }
                if (StringUtils.isBlank(workFlowSchedule.getUpdateName()) && StringUtils.isNotBlank(workFlowSchedule.getRoleId())) {
                    workFlowSchedule.setUpdateName("无在职用户");
                }
            }
            return Message.success("成功", workFlowSchedule1.getRecords(), workFlowSchedule1.getTotal(), workFlowSchedule1.getPages());
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "失败");
        }

    }

}

